<template>
	<el-form ref="loginForm" :model="formData" :rules="formRules" label-width="0" size="large">
		<el-form-item prop="account">
			<el-input v-model="formData.account" clearable placeholder="请输入账号/手机号">
				<template #prepend>
					<el-button :icon="User" />
				</template>
			</el-input>
		</el-form-item>
		<el-form-item prop="password" class="!mb-[10px]">
			<el-input v-model="formData.password" clearable show-password placeholder="请输入密码">
				<template #prepend>
					<el-button :icon="Lock" />
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="!mb-[5px]">
			<div class="login-forgot">
				<NuxtLink :to="{ path: '/login/forget' }">
					忘记密码？
				</NuxtLink>
			</div>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" style="width: 100%;" :loading="lock" round @click="handleLogin">登陆</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
import { ChannelEnum, LoginTypeEnum } from "@/enums/channelEnum";
import { User, Lock } from "@element-plus/icons-vue";
import { messageSuccess, messageError } from "@/utils/message";
import { login } from "@/api/login";
import useUserStore from "@/stores/user";

const props = defineProps({
	isAgreement: {
		type: Boolean,
		default: false,
	},
});

const userStore = useUserStore();

const loginForm = ref(null);

const formData = reactive({
	account: "",
	password: "",
	login_type: LoginTypeEnum.ACCOUNT,
	channel: ChannelEnum.PC,
});

const formRules = {
	account: [
		{ required: true, message: '请输入账号/手机号', trigger: 'blur' }
	],
	password: [
		{ required: true, message: '请输入密码', trigger: 'blur' }
	]
};

const { lock, apiCall: apiLogin } = useApiLock(login)
const handleLogin = async () => {
	await loginForm.value?.validate();
	if (!props.isAgreement) {
		messageError('确认已阅读并同意《服务协议》和《隐私政策》');
		return;
	}
	const data = await apiLogin(formData);
	userStore.login(data.token);
	messageSuccess('登录成功', () => {
		navigateTo("/")
	});
}

</script>
